package com.kly.smartbi.config;

import io.lettuce.core.ReadFrom;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author admin
 * @date 2025/3/31
 */
@Configuration
@ConfigurationProperties(prefix = "spring.redis.sentinel")
@Data
public class RedissonConfig {
    /**
     * nodes
     */
    private List<String> nodes;

    /**
     * masterName
     */
    private String master;

    /**
     * redisson配置
     * @return
     */
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        nodes = nodes.stream().map(node -> "redis://" + node).collect(Collectors.toList());
        config.useSentinelServers()
                .setMasterName(master)
                .addSentinelAddress(nodes.get(0), nodes.get(1), nodes.get(2));
        return Redisson.create(config);
    }


    /**
     * redis sentinel 读取配置
     * @return
     */
    @Bean
    public LettuceClientConfigurationBuilderCustomizer clientConfigurationBuilderCustomizer(){
        return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
    }
}
